import type { Base } from "../Base";
import { initWebGpu } from "../../utils/gputools";
import triangleVert from '../../shaders/triangle.vert.wgsl';
import redFragement from '../../shaders/red.frag.wgsl';
class Triangle implements Base {
    name = 'Triangle';
    description = 'A simple triangle example';
    version = '1.0.0';

    async run(el: HTMLCanvasElement) {
        const result = await initWebGpu(el);

        const pipeline = result?.device.createRenderPipeline({
            layout: 'auto',
            vertex: {
                module: result?.device.createShaderModule({
                    code: triangleVert,
                }),
                entryPoint: 'main',
            },
            fragment: {
                module: result?.device.createShaderModule({
                    code: redFragement,
                }),
                entryPoint: 'main',
                targets: [{
                    format: result?.presentationFormat,
                }],
            },
            primitive: {
                topology: 'triangle-list',
            },
        })

        function frame() {
            if (!pipeline) {
                throw new Error("Render pipeline is not initialized.");
            }
            const commandEncoder = result?.device.createCommandEncoder();
            const currentTextureView = result?.context.getCurrentTexture().createView();
            if (!currentTextureView) {
                throw new Error("Failed to get current texture view.");
            }
            const renderPass = commandEncoder?.beginRenderPass({
                colorAttachments: [{
                    view: currentTextureView,
                    clearValue: { r: 0, g: 0, b: 0, a: 1 },
                    loadOp: 'clear',
                    storeOp: 'store',
                }],
            });
            renderPass?.setPipeline(pipeline);
            renderPass?.draw(3);
            renderPass?.end();

            if (commandEncoder) {
                result?.device.queue.submit([commandEncoder.finish()]);
            }
            requestAnimationFrame(frame);
        }
        
        requestAnimationFrame(frame)
    }
    
    destroy(): void {
        // to do
    }
}

export default Triangle;